const { tapdSdk } = require('@opentapd/tplugin-core');

class Storage {
  constructor(workspaceId) {
    this.workspaceId = workspaceId;
  }

  // 保存数据
  async save(document, data) {
    data.createdAt = (new Date()).toISOString();
    data.workspaceId = this.workspaceId;
    // console.log('document', document, 'data', data);
    try {
      const res = await tapdSdk.storageSave({ document, data });
      // console.log('save result', res);

      if (res.status !== 1) {
        // throw new Error(`save error: ${res.info}`);
      }
      return res.data;
    } catch (err) {
      // console.log('save error', err.message);
      return err;
    }
  };

  // 查询数据
  async query(document, condition) {
    condition.workspaceId = this.workspaceId;
    // console.log('document', document, 'condition', condition);

    // console.log(`TAPD_API_PATH is ${process.env.TAPD_API_PATH}`);
    const res = await tapdSdk.storageQuery({ document, condition });
    // console.log('query result', res);
    if (res.status !== 1) {
      throw new Error(`query error: ${res.status}, ${res.info}`);
    }
    return res.data;
  };

  // 删除数据
  async delete(document, condition) {
    condition.workspaceId = this.workspaceId;
    // console.log('document', document, 'condition', condition);

    try {
      const res = await tapdSdk.storageDelete({ document, condition });
      // console.log('delete result', res);
      if (res.status !== 1) {
        throw new Error(`delete error: ${res.info}`);
      }
      return res.data;
    } catch (err) {
      throw new Error(`delete error: ${err.message}`);
    }
  };

  // 更新数据
  async update(document, condition, data) {
    condition.workspaceId = this.workspaceId;
    data.updatedAt = (new Date()).toISOString();
    // console.log('document', document, 'condition', condition, 'data', data);

    try {
      const res = await tapdSdk.storageUpdate({ document, condition, data });
      // console.log('update result', res);
      if (res.status !== 1) {
        throw new Error(`update error: ${res.info}`);
      }
      return res.data;
    } catch (err) {
      throw new Error(`update error: ${err.message}`);
    }
  };
}

module.exports = Storage;
